package com.tarena.luban.demo.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;

@Component
@Slf4j
public class JwtTestFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try{
            checkJwt(exchange);
        }catch (RuntimeException ex){
            //错误处理返回
            return Mono.error(ex);
            /*log.info("出现异常:{}",e.getMessage());
            String message = e.getMessage();
            String result="{\"code\":500,\"message\":"+message+"}";
            //直接拦截响应 不在这里做
            return writeError(exchange,result);*/
        }

        //正常向下
        return chain.filter(exchange);
    }

    /*private Mono<Void> writeError(ServerWebExchange exchange,String result) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
            }
        }));
    }*/

    public void checkJwt(ServerWebExchange exchange){
        ServerHttpRequest request = exchange.getRequest();
        //获取请求参数
        List<String> jwt = request.getQueryParams().get("jwt");
        if (CollectionUtils.isEmpty(jwt)){
            ///stock/abc
            throw new RuntimeException("缺少jwt");
        }
        String jwtValue = jwt.get(0);
        if (StringUtils.isEmpty(jwtValue)){
            //stock/abc?jwt
            throw new RuntimeException("jwt没有值");
        }
        if (!jwtValue.matches("^[0-9]*$")){
            //stock/abc?jwt=ak112321
            throw new RuntimeException("jwt数据格式不正确");
        }
        //stock/abc?jwt=12312
    }
}
